from fastapi import FastAPI, Request
from src.router.api import api_router
import os
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.middleware.cors import CORSMiddleware  #引入 CORS中间件模块
from src.job.panel_job import panel_job
from src import loop
from src.job.copy_job_from_aois import ScpAOIs
from src.utils.post_item import DetectLotItem, ConfItem, ScpAOIItem
from configparser import ConfigParser
from src.job.clear_lot_job import ClearLotJob
import time
from src.config import ctype
from src.utils.log import logger
from src.job.infer_job import infer_job
from src.job.lot_job import lot_job

root_path = os.path.dirname(os.path.abspath(__file__))


app = FastAPI()

#设置允许访问的域名
origins = ["*"]  #也可以设置为"*"，即为所有。

#设置跨域传参
app.add_middleware(
    CORSMiddleware, 
    allow_origins=origins,  #设置允许的origins来源
    allow_credentials=True,
    allow_methods=["*"],  # 设置允许跨域的http方法，比如 get、post、put等。
    allow_headers=["*"])  #允许跨域的headers，可以用来鉴别来源等作用。

app.mount("/static", StaticFiles(directory="dist/static"), name="static")

templates = Jinja2Templates(directory="dist")

app.include_router(api_router, prefix="/api")


scp_lot = ScpAOIs()
clear_job = ClearLotJob()


@app.on_event("startup")
async def startup_event():
    # 在启动时创建并运行异步任务
    logger.info("启动自动清理任务")
    loop.run_in_executor(None, clear_job.clear, ctype)
    # 程序一开始，启动自动拷贝任务，等待添加 aoi
    loop.run_in_executor(None, scp_lot.start)
    loop.run_in_executor(None, infer_job.run)


@app.get('/', response_class=HTMLResponse)
def index(request: Request):
    return templates.TemplateResponse('index.html', {"request": request})


# 服务配置
@app.post('/api/conf')
async def conf(item: ConfItem):
    ctype = item.ctype
    scp_type = item.scp_type
    infer_type = item.infer_type
    scp_interval = item.scp_interval
    delete_passwd = item.delete_passwd

    config = ConfigParser()

    config_file = os.path.join(root_path, 'src', 'config', 'server.ini')

    config.read(config_file)

    config.set('clear', 'ctype', str(ctype))
    config.set('lot', 'scp_type', str(scp_type))
    config.set('lot', 'infer_type', str(infer_type))

    config.set('lot', 'scp_interval', str(scp_interval))
    config.set('lot', 'delete_passwd', str(delete_passwd))

    # 修改配置文件
    with open(config_file, 'w') as file:
        config.write(file)

    # 停止之前启动的自动清理任务
    clear_job.stop.set()
    time.sleep(1)

    # 重新开始之前启动的自动清理任务
    clear_job.stop.clear()    
    loop.run_in_executor(None, clear_job.clear, ctype)

    return {"code": 0, "message": "修改配置成功"}



# aoi 手动上传文件夹分析
@app.post('/api/model/detect-lot')
async def aoi_auto(item: DetectLotItem):
    lot_path = item.lot_path
    material_code = item.material_code

    # 异步运行同步任务
    await loop.run_in_executor(None, lot_job.detect_lot, lot_path, material_code)

    return {"code": 0, "msg": "推理结束"}


# 执行远程拷贝任务
@app.post('/api/scp/start-aoi')
async def scp_start_aoi(item: ScpAOIItem):
    aoi_code = item.aoi_code
    material_code = item.material_code
    lot_name = item.lot_name
    start_time = item.start_time
    scp_lot.stop.clear()    
    loop.run_in_executor(None, scp_lot.start_aoi, aoi_code, material_code, lot_name, start_time)

    return {"msg": "远程拷贝任务开始"}


# 取消远程拷贝任务
@app.post('/api/scp/stop-aoi')
async def scp_stop_aoi(item: ScpAOIItem):
    aoi_code = item.aoi_code
    lot_name = item.lot_name
    material_code = item.material_code
    # 清除已经拷贝的数据和清空数据库
    await loop.run_in_executor(None, scp_lot.stop_aoi, aoi_code, material_code, lot_name)
    return {"msg": "取消远程拷贝任务"}


# 远程拷贝的状态
@app.get('/api/scp/status')
async def scp_stop_aoi():
    # 清除已经拷贝的数据和清空数据库
    status = await loop.run_in_executor(None, scp_lot.get_aoi_status)
    return {"status": status}